<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="月份快选">
        <el-date-picker
          v-model="selectedMonth"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择月份"
          @change="handleMonthChange"
          style="width: 180px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 280px">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['operations:dailyProfit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 统计图表 -->
    <el-card class="chart-card" v-loading="chartLoading">
      <div slot="header">
        <span>利润趋势图</span>
      </div>
      <div ref="profitChart" style="height: 350px;"></div>
    </el-card>

    <!-- 月度统计卡片 -->
    <el-row :gutter="20" class="stats-row" v-if="monthlyStats">
      <el-col :span="6">
        <el-card class="stats-card income">
          <div class="stats-title">本月总收入</div>
          <div class="stats-value">¥{{ formatMoney(monthlyStats.month_total_income) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card expense">
          <div class="stats-title">本月总支出</div>
          <div class="stats-value">¥{{ formatMoney(monthlyStats.month_total_expense) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card profit">
          <div class="stats-title">本月净利润</div>
          <div class="stats-value">¥{{ formatMoney(monthlyStats.month_actual_profit) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card avg">
          <div class="stats-title">日均利润</div>
          <div class="stats-value">¥{{ formatMoney(monthlyStats.avg_daily_profit) }}</div>
          <div class="stats-sub">{{ monthlyStats.days_count }}天数据</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 列表数据 -->
    <el-table v-loading="loading" :data="profitList" style="margin-top: 20px;" :fit="true">
      <el-table-column label="日期" align="center" prop="profitDate" min-width="100" fixed="left">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.profitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总收入" align="center" prop="totalIncome" min-width="100">
        <template slot-scope="scope">
          <span class="income-text">¥{{ formatMoney(scope.row.totalIncome) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总支出" align="center" prop="totalExpense" min-width="100">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.totalExpense) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际利润" align="center" prop="actualProfit" min-width="100">
        <template slot-scope="scope">
          <span :class="scope.row.actualProfit >= 0 ? 'profit-text' : 'loss-text'">
            ¥{{ formatMoney(scope.row.actualProfit) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="明细" align="center" prop="detailCount" min-width="60" />
      <!-- 收入明细 -->
      <el-table-column label="售前收款" align="center" prop="presaleIncome" min-width="90">
        <template slot-scope="scope">
          <span class="income-text">¥{{ formatMoney(scope.row.presaleIncome) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售中收款" align="center" prop="sellingIncome" min-width="90">
        <template slot-scope="scope">
          <span class="income-text">¥{{ formatMoney(scope.row.sellingIncome) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售后收款" align="center" prop="aftersaleIncome" min-width="90">
        <template slot-scope="scope">
          <span class="income-text">¥{{ formatMoney(scope.row.aftersaleIncome) }}</span>
        </template>
      </el-table-column>
      <!-- 支出明细 -->
      <el-table-column label="报销费用" align="center" prop="dailyReimbursement" min-width="90">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.dailyReimbursement) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="技术打款" align="center" prop="techPayment" min-width="90">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.techPayment) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="直通车费用" align="center" prop="throughTrainCost" min-width="90">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.throughTrainCost) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺费用" align="center" prop="storeOperationCost" min-width="90">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.storeOperationCost) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工资支出" align="center" prop="employeeSalary" min-width="90">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.employeeSalary) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="其他费用" align="center" prop="otherCost" min-width="90">
        <template slot-scope="scope">
          <span class="expense-text">¥{{ formatMoney(scope.row.otherCost) }}</span>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listDailyProfit, getMonthlyStats } from "@/api/operations/dailyProfit"
import * as echarts from 'echarts'

export default {
  name: "DailyProfit",
  data() {
    return {
      // 遮罩层
      loading: true,
      chartLoading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 利润列表
      profitList: [],
      // 日期范围
      dateRange: [],
      // 选中的月份
      selectedMonth: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginDate: null,
        endDate: null,
        profitMonth: null
      },
      // 月度统计
      monthlyStats: null,
      // 图表实例
      chartInstance: null
    }
  },
  created() {
    // 默认查询当前月
    const now = new Date()
    this.selectedMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
    this.queryParams.profitMonth = this.selectedMonth
    this.getList()
    this.getMonthlyStats()
  },
  mounted() {
    this.initChart()
  },
  activated() {
    // 使用 keep-alive 时，每次激活页面都刷新数据
    // 检查图表实例是否存在，不存在则重新初始化
    if (!this.chartInstance) {
      this.$nextTick(() => {
        this.initChart()
        this.getList()
        this.getMonthlyStats()
      })
    } else {
      // 图表存在则调整大小并刷新数据
      this.$nextTick(() => {
        if (this.chartInstance) {
          this.chartInstance.resize()
        }
        this.getList()
        this.getMonthlyStats()
      })
    }
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams
      }
      if (this.dateRange && this.dateRange.length === 2) {
        params.beginDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
        params.profitMonth = null
      }
      listDailyProfit(params).then(response => {
        this.profitList = response.rows
        this.total = response.total
        this.loading = false
        this.updateChart()
      })
    },
    /** 获取月度统计 */
    getMonthlyStats() {
      if (!this.queryParams.profitMonth) return
      getMonthlyStats(this.queryParams.profitMonth).then(response => {
        this.monthlyStats = response.data
      })
    },
    /** 初始化图表 */
    initChart() {
      if (!this.$refs.profitChart) {
        console.warn('图表DOM元素不存在，无法初始化')
        return
      }
      
      // 如果已有实例，先销毁
      if (this.chartInstance) {
        this.chartInstance.dispose()
        this.chartInstance = null
      }
      
      try {
        this.chartInstance = echarts.init(this.$refs.profitChart)
        window.removeEventListener('resize', this.handleResize) // 先移除旧的监听
        window.addEventListener('resize', this.handleResize)
      } catch (error) {
        console.error('初始化图表失败:', error)
      }
    },
    /** 更新图表 */
    updateChart() {
      // 如果没有数据，直接返回
      if (!this.profitList.length) {
        this.chartLoading = false
        return
      }
      
      // 如果图表实例不存在，尝试重新初始化
      if (!this.chartInstance) {
        this.$nextTick(() => {
          this.initChart()
          if (this.chartInstance && this.profitList.length) {
            this.updateChart()
          }
        })
        return
      }
      
      const dates = this.profitList.map(item => this.parseTime(item.profitDate, '{m}-{d}')).reverse()
      const incomes = this.profitList.map(item => item.totalIncome || 0).reverse()
      const expenses = this.profitList.map(item => item.totalExpense || 0).reverse()
      const profits = this.profitList.map(item => item.actualProfit || 0).reverse()

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['总收入', '总支出', '实际利润']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '总收入',
            type: 'line',
            data: incomes,
            smooth: true,
            itemStyle: { color: '#67C23A' },
            areaStyle: { opacity: 0.3 }
          },
          {
            name: '总支出',
            type: 'line',
            data: expenses,
            smooth: true,
            itemStyle: { color: '#F56C6C' },
            areaStyle: { opacity: 0.3 }
          },
          {
            name: '实际利润',
            type: 'line',
            data: profits,
            smooth: true,
            itemStyle: { color: '#409EFF' },
            lineStyle: { width: 3 }
          }
        ]
      }

      this.chartInstance.setOption(option)
      this.chartLoading = false
    },
    /** 处理窗口大小变化 */
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    },
    /** 月份改变 */
    handleMonthChange(val) {
      this.queryParams.profitMonth = val
      this.dateRange = []
      this.getList()
      this.getMonthlyStats()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
      if (this.queryParams.profitMonth) {
        this.getMonthlyStats()
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      const now = new Date()
      this.selectedMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
      this.queryParams.profitMonth = this.selectedMonth
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('operations/dailyProfit/export', {
        ...this.queryParams
      }, `日利润_${new Date().getTime()}.xlsx`)
    },
    /** 格式化金额 */
    formatMoney(val) {
      if (val == null || val === '') return '0.00'
      return parseFloat(val).toFixed(2)
    }
  }
}
</script>

<style scoped>
.chart-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
  padding: 20px 0;
}

.stats-card.income {
  border-left: 4px solid #F56C6C;
}

.stats-card.expense {
  border-left: 4px solid #67C23A;
}

.stats-card.profit {
  border-left: 4px solid #409EFF;
}

.stats-card.avg {
  border-left: 4px solid #E6A23C;
}

.stats-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-sub {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.income-text {
  color: #F56C6C;
  font-weight: bold;
}

.expense-text {
  color: #67C23A;
  font-weight: bold;
}

.profit-text {
  color: #409EFF;
  font-weight: bold;
}

.loss-text {
  color: #F56C6C;
  font-weight: bold;
}
</style>

